package com.itheima.lucene;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

//lucene的高亮显示
public class HighlighterTest {
    public static void main(String[] args) throws IOException, ParseException, InvalidTokenOffsetsException {
        //创建索引查询核心对象
        IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File("F:\\workspace27\\lucene\\index")));
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //封装查询条件
        QueryParser queryParser = new QueryParser("content", new IKAnalyzer());
        Query query = queryParser.parse("勇士");
        //封装高亮参数,创建一个对象
        QueryScorer queryScorer = new QueryScorer(query);
        SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<font color ='red'>", "</font>");
        Highlighter highlighter = new Highlighter(simpleHTMLFormatter, queryScorer);
        //排序,默认是升序
        Sort sort = new Sort(new SortField("pid", SortField.Type.LONG,true));
        TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE,sort);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;//得分文档的数据
        int totalHits = topDocs.totalHits;
        for (ScoreDoc scoreDoc : scoreDocs) {
            float score = scoreDoc.score;//文档的得分

            int docPid = scoreDoc.doc; // 文档内容的pid
            Document document = indexSearcher.doc(docPid);

            String pid = document.get("pid");
            String pname = document.get("pname");
            String content = document.get("content");
            String highlightContent = highlighter.getBestFragment(new IKAnalyzer(), "content", content);
            if (highlightContent != null) {
                content = highlightContent;
            }
            System.out.println("文档的得分为:" + score + ";文档的id为:" + pid + ";文档的名称:" + pname + "; 文档的内容:" + content);
        }

    }








}
